import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useUserStore } from "./usersStore"
import { insertCartAPI, findNewCartListAPI, removeCartAPI, updateCartAPI } from "@/apis/cart"
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import router from "@/router"
export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    // 统一登录检查方法
    const checkLogin = () => {
        if (!isLogin.value) {
            ElMessage.warning('请先登录')
            router.replace('/login')
            return false
        }
        return true
    }
    // 更新购物车数据
    const refreshCart = async () => {
        const res = await findNewCartListAPI(userStore.userInfo.id)
        cartList.value = res.data
    }
    //添加购物车
    const addCart = async (goods) => {
        if (!checkLogin()) return // 登录拦截
        const item = cartList.value.find((item) => goods.skuId == item.skuId)
        if (item) {
            //添加过
            item.count += goods.count
            const { skuId, count, selected } = item
            await updateCartAPI({ skuId, count, selected })
        } else {
            //未添加过
            await insertCartAPI({ goods })
        }
        await refreshCart()
    }
    //单选
    const singleCheck = async (skuId, selected) => {
        if (!checkLogin()) return // 登录拦截
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
        await updateCartAPI({ skuId, selected })
    }
    //删除购物车数据
    const removeCart = async (skuId) => {
        if (!checkLogin()) return // 登录拦截
        await removeCartAPI(skuId)
        refreshCart()
    }
    //全选功能
    const allCheck = async (selected) => {
        if (!checkLogin()) return // 登录拦截
        // 批量更新选中状态
        await Promise.all(
            cartList.value.map(item =>
                updateCartAPI({ skuId: item.skuId, selected })
            ))
        await refreshCart()
    }
    //总量
    const allCount = computed(() => {
        return cartList.value.reduce((a, c) => a + c.count, 0)
    })
    //总价
    const allPrice = computed(() => {
        return cartList.value.reduce((a, c) => a + c.price * c.count, 0)
    })
    //选中数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    //选中商品价钱
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.price * c.count, 0))
    //是否全选
    const isAll = computed(() => {
        return cartList.value.every((item) => item.selected)
    })
    //退出时，清空购物车
    const clearCart = () => {
        cartList.value = []
    }
    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedPrice,
        singleCheck,
        addCart,
        removeCart,
        allCheck,
        refreshCart,
        clearCart
    }
},
    {
        persist: true
    }
)